package cc.cary.warehouse;

import cc.cary.warehouse.config.Config;
import com.dtflys.forest.springboot.annotation.ForestScan;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.*;
import java.util.stream.Collectors;

@SpringBootApplication
@MapperScan("cc.cary.warehouse.mapper")
@ForestScan(basePackages = "cc.cary.warehouse.client")
@Slf4j
public class WarehouseApplication {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(WarehouseApplication.class);
        ConfigurableApplicationContext context = app.run(args);
        int port = Integer.parseInt(Optional.ofNullable(context.getEnvironment().getProperty("server.port")).orElse("0"));
        log.info("Swagger2 v3.0 started. http://localhost:" + port + "/swagger-ui.html");
        dumpEnv(context);
    }

    /**
     * 打印配置信息
     *
     * @param context
     */
    private static void dumpEnv(ConfigurableApplicationContext context) {
        Map<String, Set<String>> configKey = new HashMap<>();
        context.getEnvironment().getPropertySources().stream()
                .filter(propertySource -> propertySource.getName().startsWith("applicationConfig:")
                        && propertySource.getSource() instanceof Map)
                .forEach(propertySource -> {
                    Set<String> keys = configKey.computeIfAbsent(propertySource.getName(), k -> new HashSet<>());
                    ((Map<?, ?>) propertySource.getSource()).keySet().stream()
                            .map(String::valueOf)
                            .forEach(keys::add);
                });

        Set<String> allKeys = configKey.values().stream()
                .flatMap(Collection::stream)
                .collect(Collectors.toSet());

        log.info("=== show springboot application-configure. [active:{}] === ", Config.get("spring.profiles.active"));
        allKeys.forEach(v -> {
            log.info("==> {} = {}", v, Config.get(v));
        });
    }
}
